<?php

namespace addons\kzvote\controller;

use addons\kzvote\library\WechatService;
use addons\kzvote\model\UserModel;
use addons\third\library\Application;
use addons\third\library\Service;
use app\common\library\Token;
use app\common\model\kzvote\Vote;

/**
 * 公众号接口
 */
class Wechat extends Base
{
    protected $noNeedLogin = ['login','config'];
    protected $visibleFields = ['id', 'avatar', 'gender', 'nickname', 'mobile', 'birthday', 'status', 'createtime', 'logintime'];

    public function _initialize()
    {
        parent::_initialize();
        $config = get_addon_config('third');
        $this->app = new Application($config);
    }

    /**
     * 公众号授权
     */
    public function login()
    {
        $code = input('code/s', '');
        if (!$code) {
            $this->error('缺少参数code');
        }
        /*
        $service = new WechatService();
        $oauth_user = $service->login();
        if (!$oauth_user){
            $this->error('授权失败');
        }
        $openid = UserModel::oauth($oauth_user);
        if (empty($openid)) {
            $user = UserModel::fastRegister($oauth_user,'wechat');
            if (!$user) {
                $this->error('注册用户失败');
            }
        }else{
            if (!$openid['open_id']){
                $openid->open_id = $oauth_user['openid'];
                $openid->save();
            }
            $user = UserModel::get($openid['user_id']);
        }
        if (!$user){
            $this->error('注册用户失败');
        }
        */
        $platform = $this->request->param('platform', "wechat");
        $service = new WechatService();
        $thirdinfo = $service->login();
        if (!$thirdinfo){
            $this->error('授权失败');
        }

        $thirdinfo['platform'] = $platform;
        $thirdinfo['openid'] = $thirdinfo["raw"]['openid'] ?? '';
        $thirdinfo['unionid'] = $thirdinfo["raw"]['unionid'] ?? '';

        //判断是否需要绑定
        $isBind = Service::isBindThird($thirdinfo['platform'], $thirdinfo['openid'], Service::getApptype(), $thirdinfo['unionid']);
        Service::connect($thirdinfo['platform'], $thirdinfo);
        $user = $this->auth->getUserinfo();
        // 清除之前的token
        Token::clear($user["id"]);

        // 直接登录
        $this->auth->direct($user["id"]);

        $this->success('', [
            'token' => $this->auth->getToken(),
            'user' => $user,
        ]);
    }

    /**
     * 公众号配置
     */
    public function config(){
        $url = $this->request->param('url');
        $service = new WechatService();
        $this->success('',$service->jssdk(urldecode($url)));
    }


}
